package io.renren.modules.erp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.constants.BusinessConstants;
import io.renren.common.exception.JshException;
import io.renren.common.utils.DateTimeUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.RandomString;
import io.renren.common.utils.StringUtil;
import io.renren.modules.erp.dao.*;
import io.renren.modules.erp.entity.*;
import io.renren.modules.erp.service.*;
import io.renren.modules.erp.vo.*;
import net.sf.json.JSONArray;
import org.apache.http.HttpStatus;
import org.flowable.editor.language.json.converter.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service("sellOrderService")
public class SellOrderServiceImpl extends ServiceImpl<SellOrderMapper, SellOrder> implements SellOrderService {
    private Logger logger = LoggerFactory.getLogger(SellOrderServiceImpl.class);

    @Autowired
    private SellOrderMapper sellOrderMapper;
    @Autowired
    private ProductInfoMapper  productInfoMapper;
    @Autowired
    SellOrderService sellOrderService;
    @Autowired
    ProductInfoService productInfoService;
    @Autowired
    DepotHeadService depotHeadService;
    @Autowired
    SupplierService supplierService;
    @Autowired
    SupplierMapper supplierMapper;
    @Autowired
    DepotItemService depotItemService;
    @Autowired
    MaterialService materialService;
    @Autowired
    MaterialExtendService  materialExtendService;

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertSellOrder(Long userId)  {
        int result=0;
       //取出这个字段为0的数据
        List<SellOrder> listOrder= sellOrderMapper.selectList(new QueryWrapper<SellOrder>().eq("is_order_number",0));

        if(listOrder.size()==0||listOrder==null){
            result=1;
            return result;

        }
        List<Supplier> list = supplierService.list();
        List<String> supperNames = list.stream().map(Supplier::getSupplier).collect(Collectors.toList());  // 数据库里的
        List<String> collect1 = listOrder.stream().map(SellOrder::getMemberUsername).collect(Collectors.toList());
        List<Supplier> suppliers = new ArrayList<>();

        for (String s : collect1) {
            boolean contains = supperNames.contains(s);
            if (!contains){
                Supplier supplier = new Supplier();
                supplier.setSupplier(s);
                suppliers.add(supplier);
            }
        }
        if (CollectionUtils.isNotEmpty(suppliers)){
            supplierService.saveBatch(suppliers);
        }

        List<DepotHead> collect = listOrder.stream().map(item -> {
            DepotHead depotHead = new DepotHead();
            depotHead.setCreateTime(item.getCreateTime().toString());
            depotHead.setExternalNumber(item.getOrderSn());
            depotHead.setContacts(item.getReceiverName());
            depotHead.setPhoneNum(item.getReceiverPhone());
            depotHead.setDeliverAddress(item.getReceiverDetailAddress());
            depotHead.setSupplier(item.getMemberUsername());
            depotHead.setTotalPrice(item.getTotalAmount());
            depotHead.setDocumentStatus(item.getStatus().toString());
            depotHead.setDefaultNumber("XSDD"+ DateTimeUtils.getCurrentDateString().substring(2,8)+ RandomString.getSixRandomString());
            depotHead.setNumber("XSDD"+ DateTimeUtils.getCurrentDateString().substring(2,8)+ RandomString.getSixRandomString());
            depotHead.setType("其他");
            depotHead.setSubType("销售订单");
            depotHead.setStatus("0");
//            depotHead.setTenantId(item.getTenantId());
            depotHead.setDeleteFlag("0");
            depotHead.setServiceType("线上");
            depotHead.setCreator(userId);
            return depotHead;
        }).collect(Collectors.toList());
        depotHeadService.saveBatch(collect);

        List<SellOrder> collect2 = listOrder.stream().peek(item -> {
            item.setIsOrderNumber(1);
        }).collect(Collectors.toList());
        sellOrderService.updateBatchById(collect2);
        //取出本次商城订单过来数据的ordersn来查出订单商品
        List<String> collect3 = listOrder.stream().map(SellOrder::getOrderSn).collect(Collectors.toList());
        List<ProductInfo> listProduct=  productInfoMapper.selectList(new QueryWrapper<ProductInfo>().in("order_sn",collect3));

        //订单编号 orderSn;
        //货品编码  String productNum;
        List<DepotItem> depotItemList  = new ArrayList<>();
        List<Material> materialList  = new ArrayList<>();
        List<MaterialExtend> materialExtendList  = new ArrayList<>();
        List<DepotItem> collect4 = listProduct.stream().map(item -> {
            DepotItem depotItem=new DepotItem();
            Material  material=new Material();
            MaterialExtend materialExtend=new MaterialExtend();
            depotItem.setHeaderId((long) 1111111);
            depotItem.setMaterialId(item.getSkuId());
            depotItem.setUnitPrice(item.getSkuPrice());
            depotItem.setOperNumber(item.getSkuQuantity());
            depotItem.setAllPrice(item.getRealAmount());


            material.setId(item.getSkuId());
            material.setName(item.getSkuName());

            materialExtend.setMaterialId(item.getSkuId());
            materialExtend.setBarCode(item.getProductNum());
            depotItemList.add(depotItem);
            materialList.add(material);
            materialExtendList.add(materialExtend);
              return depotItem;
        }).collect(Collectors.toList());
        depotItemService.saveBatch(depotItemList);
        materialService.saveBatch(materialList);
        materialExtendService.saveBatch(materialExtendList);
       return result;
    }

    //获取商城订单和商品数据，并插入erp暂存的草稿表中
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void insertOrderProduct(String a1) {
        JSONArray jsonArray = JSONArray.fromObject(a1);
        List<OrderProductVo> list1=  (List<OrderProductVo>) jsonArray.toCollection(jsonArray, OrderProductVo.class);

        Map<String, List<OrderProductVo>> collect = list1.stream().collect(Collectors.groupingBy(OrderProductVo::getOrderSn));
        List<SellOrder> sellOrderVos = new ArrayList<>();
        List<ProductInfo> productInfoList  = new ArrayList<>();

        for (Map.Entry<String, List<OrderProductVo>> entry : collect.entrySet()){
            List<OrderProductVo> productVos = entry.getValue();
            // 1、封装SPU基本信息
            SellOrder sellOrder = new SellOrder();
            sellOrder.setOrderSn(productVos.get(0).getOrderSn());
            sellOrder.setCreateTime(productVos.get(0).getCreateTime());
            sellOrder.setIsOrderNumber(0);
            sellOrder.setMemberUsername(productVos.get(0).getMemberUsername());
            sellOrder.setReceiverDetailAddress(productVos.get(0).getReceiverDetailAddress());
            sellOrder.setReceiverName(productVos.get(0).getReceiverName());
            sellOrder.setReceiverPhone(productVos.get(0).getReceiverPhone());
            sellOrder.setStatus(productVos.get(0).getStatus());
            sellOrder.setTotalAmount(productVos.get(0).getTotalAmount());
            sellOrderVos.add(sellOrder);
            List<ProductInfo> productInfoVos = productVos.stream().map(item -> {
                // SKU销售属性
                ProductInfo productInfo = new ProductInfo();
                productInfo.setProductNum(item.getProductNum());
                productInfo.setRealAmount(item.getRealAmount());
                productInfo.setSkuAttrsVals(item.getSkuAttrsVals());
                productInfo.setSkuId(item.getSkuId());
                productInfo.setSkuName(item.getSkuName());
                productInfo.setSkuPrice(item.getSkuPrice());
                productInfo.setSkuQuantity(item.getSkuQuantity());
                productInfo.setOrderSn(item.getOrderSn());
                productInfoList.add(productInfo);
                return productInfo;
            }).collect(Collectors.toList());
//            productInfoService.saveBatch(productInfoVos);
        }
        productInfoService.saveBatch(productInfoList);
        sellOrderService.saveBatch(sellOrderVos);
    }
}
